package com.itboye.sunsunhome.www.aq.base;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

/**
 * Created by 赵武 on 2015/3/12.
 * 日期：2015-05-05
 * 		1. 丢弃无密码的广播
 */
public class AqDeviceFind {
	public DatagramSocket mUdpSocket = null;
	public int mUdpPort = 0;
	public Thread mThread = null;
	private boolean mThreadIsRun = false;
	public Handler mHandler;

	public AqDeviceFind(Handler handler) {
		mHandler = handler;
	}

	public boolean isRun() {
		if (mThread == null) {
			return false;
		}
		return mThreadIsRun;
	}

	/**
	 * 开始查找设备
	 *
	 * @param port 监听端口，默认15151
	 * @return 已经运行或者运行失败返回false，成功返回true
	 */
	public boolean start(int port) {
		// 避免重复运行
		if (isRun()) {
			return false;
		}
		mThreadIsRun = true;
		mUdpPort = port;
		mThread = new Thread(new Runnable() {
			@Override
			public void run() {
				// 变量
				byte[] datar = new byte[1024];
				DatagramPacket dpr = null;
				// 创建UDP
				try {
					dpr = new DatagramPacket(datar, datar.length);
					mUdpSocket = new DatagramSocket(mUdpPort, InetAddress.getByName("0.0.0.0"));
					mUdpSocket.setBroadcast(true);
					mUdpSocket.setSoTimeout(2);
				} catch (SocketException e) {
					mThread.interrupt();
				} catch (UnknownHostException e) {
					mThread.interrupt();
				}
				// 接收循环
				while (!Thread.currentThread().isInterrupted()) {
					try {
						mUdpSocket.receive(dpr);
						// 数据处理
						byte[] dt = dpr.getData();
						// 校验
						if (dpr.getLength() < 2) {
							continue;
						}
						for (int i = 0; i < dpr.getLength(); i++) {
							dt[i] ^= (byte) 0xa5;
						}
						int sum1 = 0;
						int sum2 = 0;
						for (int i = 0; i < (dpr.getLength() - 2); i++) {
							int x = 0;
							x |= dt[i];
							sum1 += x;
						}
						sum1 &= 0xffff;
						sum2 |= dt[dpr.getLength() - 2];
						sum2 <<= 8;
						sum2 &= 0xff00;
						sum2 |= dt[dpr.getLength() - 1] & 0xff;
						if (sum1 == sum2) {
							// 校验正确
							// 提取MAC、密码、IP
							AqDeviceInfo devInfo = new AqDeviceInfo();
							devInfo.mLanIp = dpr.getAddress().getHostAddress();
							String packStr = new String(dt, 0, dt.length - 2, "UTF-8");
							String[] packLine = packStr.split("\n");
							for (int i = 0; i < packLine.length; i++) {
								String str1 = packLine[i];
								String str2 = str1.replace('\r', '\0');
								if (str2.length() >= 1) {
									String str3 = str2.substring(1);
									switch (str2.charAt(0)) {
										case 'p':
											devInfo.mPassword = str3;
											break;
										case 'm':
											devInfo.mMacAddress = str3;
											break;
										case 'u':
											devInfo.mDid = str3;
											break;
										default:
											break;
									}
								}
							}
							if (devInfo.mPassword.compareTo("") != 0) {
								// 传递消息
								AqDeviceMessage msgObj = new AqDeviceMessage();
								msgObj.mDevice = null;
								msgObj.mCommandItem = null;
								msgObj.mDeviceInfo = devInfo;
								msgObj.mMessageType = AqDeviceMessage.AqDeviceMessageType.FindLanDevice;
								Message msg = new Message();
								msg.obj = msgObj;
								msg.what = MessageWhat.DeviceMessage;
								sendMessage(msg);
							}
						}
					} catch (IOException e) {
						try {
							Thread.sleep(20);
						} catch (InterruptedException e1) {
							// 被中断则退出线程，并且关闭UDP
							if (mUdpSocket != null) {
								mUdpSocket.close();
							}
							mThreadIsRun = false;
							return;
						}
					}
				}
				// 关闭UDP
				if (mUdpSocket != null) {
					mUdpSocket.close();
				}
				mThreadIsRun = false;
			}
		});
		mThread.start();
		return true;
	}

	private void sendMessage(Message msg) {
		if (mHandler != null) {
			mHandler.sendMessage(msg);
		}
	}

	public boolean stop() {
		if (isRun()) {
			mThread.interrupt();
			try {
				mThread.join();
			} catch (InterruptedException e) {
			}
			return true;
		}
		return false;
	}
}
